package com.whz.governance.sensitive.utils;

import com.alibaba.csp.sentinel.property.PropertyListener;
import com.whz.generic.spring.SpringUtils;
import com.whz.governance.sensitive.SensitiveEnum;
import com.whz.governance.sensitive.SensitiveStoreLoader;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author whz
 */
@Slf4j
@UtilityClass
public class ConfigLoaderUtils {

    /**
     * 订阅敏感数据变化
     *
     * @param sensitiveEnum    敏感数据类型
     * @param propertyListener 敏感数据变化监听器
     */
    public void loadConfigAndListenChanged(SensitiveEnum sensitiveEnum,
                                           PropertyListener<List<String>> propertyListener) {
        SpringUtils.getBean(SensitiveStoreLoader.class).ifPresent(sensitiveStoreLoader -> {
            try {
                sensitiveStoreLoader.loadConfigAndListenChanged(sensitiveEnum, propertyListener);
            } catch (Exception exception) {
                log.error("loadConfigAndListenChanged '" + sensitiveEnum + "' error.", exception);
            }
        });
    }

    /**
     * 监听IP的黑名单的变化
     *
     * @param propertyListener 数据变化监听器
     */
    public void loadIpBlackListChanged(PropertyListener<List<String>> propertyListener) {
        loadConfigAndListenChanged(SensitiveEnum.IP_BLACK, propertyListener);
    }

    /**
     * 监听IP的黑名单的变化
     *
     * @param propertyListener 数据变化监听器
     */
    public void loadIpWhiteListChanged(PropertyListener<List<String>> propertyListener) {
        loadConfigAndListenChanged(SensitiveEnum.IP_WHITE, propertyListener);
    }
}